// 等待DOM加载完成
document.addEventListener('DOMContentLoaded', function() {
  // 处理导航栏滚动效果
  window.addEventListener('scroll', function() {
    const navbar = document.querySelector('.navbar');
    if (window.scrollY > 50) {
      navbar.classList.add('bg-white', 'shadow-md');
      navbar.classList.remove('bg-transparent');
    } else {
      navbar.classList.add('bg-white');
      navbar.classList.remove('shadow-md', 'bg-transparent');
    }
  });

  // 移动端导航菜单控制
  const navbarToggler = document.querySelector('.navbar-toggler');
  const navbarNav = document.querySelector('#navbarNav');
  
  navbarToggler.addEventListener('click', function() {
    navbarNav.classList.toggle('show');
  });

  // 点击导航链接关闭移动端菜单
  const navLinks = document.querySelectorAll('.nav-link');
  navLinks.forEach(link => {
    link.addEventListener('click', function() {
      if (navbarNav.classList.contains('show')) {
        navbarNav.classList.remove('show');
      }
    });
  });

  // 关于我们冒泡弹窗 - 阻止内部按钮点击事件冒泡
  const dropdownItems = document.querySelectorAll('.dropdown-item');
  dropdownItems.forEach(item => {
    item.addEventListener('click', function(e) {
      e.preventDefault();
      e.stopPropagation();
      // 这里可以添加按钮点击后的逻辑
      console.log('Dropdown item clicked:', this.textContent);
    });
  });

  // 新闻分类筛选功能
  const categoryBtns = document.querySelectorAll('.category-btn');
  const newsItems = document.querySelectorAll('.news-item');
  
  categoryBtns.forEach(btn => {
    btn.addEventListener('click', function() {
      // 移除所有按钮的active类
      categoryBtns.forEach(b => b.classList.remove('active'));
      // 给当前按钮添加active类
      this.classList.add('active');
      
      const category = this.getAttribute('data-category');
      
      // 筛选新闻
      newsItems.forEach(item => {
        if (category === 'all' || item.getAttribute('data-category') === category) {
          item.style.display = 'flex';
          // 添加动画效果
          setTimeout(() => {
            item.style.opacity = '1';
            item.style.transform = 'translateY(0)';
          }, 50);
        } else {
          item.style.opacity = '0';
          item.style.transform = 'translateY(20px)';
          setTimeout(() => {
            item.style.display = 'none';
          }, 300);
        }
      });
    });
  });

  // 搜索功能
  const searchBtn = document.querySelector('.search-btn');
  const searchInput = document.querySelector('.search-input');
  
  searchBtn.addEventListener('click', function() {
    performSearch();
  });
  
  searchInput.addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
      performSearch();
    }
  });
  
  function performSearch() {
    const searchTerm = searchInput.value.trim().toLowerCase();
    if (searchTerm === '') return;
    
    // 搜索逻辑
    newsItems.forEach(item => {
      const title = item.querySelector('.news-title a').textContent.toLowerCase();
      const excerpt = item.querySelector('.news-excerpt').textContent.toLowerCase();
      
      if (title.includes(searchTerm) || excerpt.includes(searchTerm)) {
        item.style.display = 'flex';
        item.style.opacity = '1';
        item.style.transform = 'translateY(0)';
      } else {
        item.style.opacity = '0';
        item.style.transform = 'translateY(20px)';
        setTimeout(() => {
          item.style.display = 'none';
        }, 300);
      }
    });
    
    // 滚动到结果顶部
    window.scrollTo({
      top: document.querySelector('.news-content').offsetTop - 100,
      behavior: 'smooth'
    });
  }

  // 分页控制功能
  const paginationBtns = document.querySelectorAll('.pagination-btn:not(.prev-btn):not(.next-btn)');
  const prevBtn = document.querySelector('.prev-btn');
  const nextBtn = document.querySelector('.next-btn');
  
  // 分页按钮点击事件
  paginationBtns.forEach(btn => {
    btn.addEventListener('click', function() {
      // 移除所有分页按钮的active类
      paginationBtns.forEach(b => b.classList.remove('active'));
      // 给当前按钮添加active类
      this.classList.add('active');
      
      // 更新上一页/下一页按钮状态
      updatePaginationButtons();
      
      // 模拟加载新页面的内容
      simulatePageLoad();
    });
  });
  
  // 上一页按钮点击事件
  prevBtn.addEventListener('click', function() {
    if (this.classList.contains('disabled')) return;
    
    // 找到当前激活的按钮
    const activeBtn = document.querySelector('.pagination-btn.active:not(.next-btn):not(.prev-btn)');
    const activeIndex = Array.from(paginationBtns).indexOf(activeBtn);
    
    if (activeIndex > 0) {
      paginationBtns[activeIndex - 1].click();
    }
  });
  
  // 下一页按钮点击事件
  nextBtn.addEventListener('click', function() {
    if (this.classList.contains('disabled')) return;
    
    // 找到当前激活的按钮
    const activeBtn = document.querySelector('.pagination-btn.active:not(.next-btn):not(.prev-btn)');
    const activeIndex = Array.from(paginationBtns).indexOf(activeBtn);
    
    if (activeIndex < paginationBtns.length - 1) {
      paginationBtns[activeIndex + 1].click();
    }
  });
  
  // 更新分页按钮状态
  function updatePaginationButtons() {
    // 找到当前激活的按钮
    const activeBtn = document.querySelector('.pagination-btn.active:not(.next-btn):not(.prev-btn)');
    const activeIndex = Array.from(paginationBtns).indexOf(activeBtn);
    
    // 更新上一页按钮状态
    if (activeIndex === 0) {
      prevBtn.classList.add('disabled');
    } else {
      prevBtn.classList.remove('disabled');
    }
    
    // 更新下一页按钮状态
    if (activeIndex === paginationBtns.length - 1) {
      nextBtn.classList.add('disabled');
    } else {
      nextBtn.classList.remove('disabled');
    }
  }
  
  // 模拟加载新页面的内容
  function simulatePageLoad() {
    // 显示加载指示器（可以根据需要添加）
    const newsList = document.querySelector('.news-list');
    
    // 模拟加载延迟
    setTimeout(() => {
      // 在实际应用中，这里应该是通过API获取新的新闻内容
      // 这里仅作演示，滚动到顶部
      newsList.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }, 500);
  }
  
  // 初始化分页按钮状态
  updatePaginationButtons();

  // 订阅表单处理
  const subscribeForm = document.querySelector('.subscribe-form');
  
  subscribeForm.addEventListener('submit', function(e) {
    e.preventDefault();
    
    const emailInput = document.querySelector('.subscribe-input');
    const email = emailInput.value.trim();
    
    if (!email) {
      alert('请输入您的邮箱地址');
      return;
    }
    
    // 简单的邮箱验证
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      alert('请输入有效的邮箱地址');
      return;
    }
    
    // 模拟订阅成功
    alert('订阅成功！我们会定期向您发送最新的新闻资讯。');
    emailInput.value = '';
    
    // 在实际应用中，这里应该是通过API发送订阅请求
    console.log('订阅邮箱:', email);
  });

  // 热门新闻点击效果
  const hotNewsItems = document.querySelectorAll('.hot-news-item');
  hotNewsItems.forEach(item => {
    item.addEventListener('click', function(e) {
      if (e.target.tagName === 'A') {
        // 可以在这里添加点击热门新闻的统计或其他逻辑
        console.log('点击热门新闻:', e.target.textContent);
      }
    });
  });

  // 最新资讯点击效果
  const latestNewsItems = document.querySelectorAll('.latest-news-item');
  latestNewsItems.forEach(item => {
    item.addEventListener('click', function(e) {
      if (e.target.tagName === 'A') {
        // 可以在这里添加点击最新资讯的统计或其他逻辑
        console.log('点击最新资讯:', e.target.textContent);
      }
    });
  });

  // 新闻项悬停效果增强
  newsItems.forEach(item => {
    item.addEventListener('mouseenter', function() {
      this.style.borderColor = '#007ac9';
    });
    
    item.addEventListener('mouseleave', function() {
      this.style.borderColor = '#eee';
    });
  });

  // 平滑滚动（保留默认跳转行为）
  document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function() {
      const targetId = this.getAttribute('href');
      if (targetId === '#') return;
      
      const targetElement = document.querySelector(targetId);
      if (targetElement) {
        window.scrollTo({
          top: targetElement.offsetTop - 80,
          behavior: 'smooth'
        });
      }
    });
  });

  // 添加返回顶部按钮功能（可选）
  const backToTopBtn = document.createElement('button');
  backToTopBtn.className = 'back-to-top';
  backToTopBtn.innerHTML = '↑';
  backToTopBtn.style.cssText = `
    position: fixed;
    bottom: 30px;
    right: 30px;
    width: 50px;
    height: 50px;
    border-radius: 50%;
    background-color: #007ac9;
    color: white;
    border: none;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
    opacity: 0;
    visibility: hidden;
    transition: all 0.3s ease;
    z-index: 9999;
  `;
  document.body.appendChild(backToTopBtn);
  
  // 监听滚动事件，显示或隐藏返回顶部按钮
  window.addEventListener('scroll', function() {
    if (window.pageYOffset > 500) {
      backToTopBtn.style.opacity = '1';
      backToTopBtn.style.visibility = 'visible';
    } else {
      backToTopBtn.style.opacity = '0';
      backToTopBtn.style.visibility = 'hidden';
    }
  });
  
  // 返回顶部按钮点击事件
  backToTopBtn.addEventListener('click', function() {
    window.scrollTo({
      top: 0,
      behavior: 'smooth'
    });
  });

  // 初始化页面时添加动画效果
  function initPageAnimation() {
    // 为新闻列表项添加渐入效果
    newsItems.forEach((item, index) => {
      item.style.opacity = '0';
      item.style.transform = 'translateY(20px)';
      item.style.transition = 'opacity 0.5s ease, transform 0.5s ease';
      
      setTimeout(() => {
        item.style.opacity = '1';
        item.style.transform = 'translateY(0)';
      }, 100 * (index + 1));
    });
    
    // 为侧边栏元素添加动画效果
    const sidebarSections = document.querySelectorAll('.sidebar-section');
    sidebarSections.forEach((section, index) => {
      section.style.opacity = '0';
      section.style.transform = 'translateX(20px)';
      section.style.transition = 'opacity 0.5s ease, transform 0.5s ease';
      
      setTimeout(() => {
        section.style.opacity = '1';
        section.style.transform = 'translateX(0)';
      }, 300 + (index * 100));
    });
  }
  
  // 初始化页面动画
  initPageAnimation();
});